using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Security;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;
using FredCK.FCKeditorV2;
using MB.TheBeerHouse;

namespace MB.TheBeerHouse.UI.Admin
{
   public partial class AddEditProduct : BasePage
   {
      protected string myIsbn, myAuthor, myTitle, myPublisher, myLanguage;
      protected int myNumber;

      protected void Page_Load(object sender, EventArgs e)
      {
         if (!this.IsPostBack)
         {
            // if a ID param is present on the querystring, switch to Edit mode for that product,
            // but only after checking that the current user is an Administrator or an Editor
            if (!string.IsNullOrEmpty(this.Request.QueryString["ID"]))
            {
               if (this.User.Identity.IsAuthenticated &&
                  (this.User.IsInRole("Administrators") || this.User.IsInRole("Editors")))
               {
                  dvwProduct.ChangeMode(DetailsViewMode.Edit);
                  UpdateTitle();
               }
               else
                  throw new SecurityException("You are not allowed to edit existent products!");
            }
         }
      }

      protected void dvwProduct_ItemCreated(object sender, EventArgs e)
      {
         Control ctl = dvwProduct.FindControl("txtDescription");
         if (ctl != null)
         {
            FCKeditor txtDescription = ctl as FCKeditor;
            txtDescription.BasePath = this.BaseUrl + "FCKeditor/";
         }
      }

      protected void dvwProduct_DataBound(object sender, EventArgs e)
      {
         // Tn InserMode, set the UnitsInStock to 1000000 and DiscountPercentage to 0
         if (dvwProduct.CurrentMode == DetailsViewMode.Insert)
         {
            (dvwProduct.FindControl("txtUnitsInStock") as TextBox).Text = "1000000";
            (dvwProduct.FindControl("txtDiscountPercentage") as TextBox).Text = "0";
         }
      }

      protected void dvwProduct_ModeChanged(object sender, EventArgs e)
      {
         UpdateTitle();
      }

      private void UpdateTitle()
      {
         lblNewProduct.Visible = (dvwProduct.CurrentMode == DetailsViewMode.Insert);
         lblEditProduct.Visible = !lblNewProduct.Visible;
      }
      protected void fetchBtn_Click(object sender, EventArgs e)
      {
          try
          {
              ((Button)dvwProduct.FindControl("fetchBtn")).Enabled = false;
              System.Net.WebClient client = new System.Net.WebClient();
              //myIsbn = "0316769487";
              myIsbn = ((TextBox)dvwProduct.FindControl("txtISBN")).Text.Replace(" ", "");
              myIsbn = myIsbn.Replace("-", "");
              ((TextBox)dvwProduct.FindControl("txtISBN")).Text = myIsbn;

              // Initialize data
              myPublisher = "not found";
              myTitle = "not found";
              myAuthor = "not found";
              string bookInfoFetchDataFile = ConfigurationManager.AppSettings.Get("bookInfoFetchDataFile");

              bookInfoFetchDataFile = MapPath(bookInfoFetchDataFile);

              System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
              doc.Load(bookInfoFetchDataFile);
              bool titleFound = false, authorFound = false, publisherFound = false;
              foreach (System.Xml.XmlElement site in doc.SelectNodes("/BookSites/Site"))
              {
                  // Get patterns
                  string urlFormat = site.SelectSingleNode("UrlFormat").InnerText;
                  string titleAuthorPattern = site.SelectSingleNode("TitleAuthorPattern").InnerText;
                  string publisherPattern = site.SelectSingleNode("PublisherPattern").InnerText;
                  // Get page
                  byte[] buffer = client.DownloadData(string.Format(urlFormat, myIsbn));
                  Encoding encoding = Encoding.GetEncoding("iso8859-1");
                  string htmlDoc = encoding.GetString(buffer);
                  // Match patterns
                  Match titleAuthorInfo = Regex.Match(htmlDoc, titleAuthorPattern);
                  Match publisherInfo = Regex.Match(htmlDoc, publisherPattern);

                  if (titleAuthorInfo.Success)
                  {
                      if (!titleFound)
                      {
                          myTitle = titleAuthorInfo.Groups["title"].Value.Trim();
                          if (!string.IsNullOrEmpty(myTitle))
                          {
                              titleFound = true;
                          }
                      }
                      if (!authorFound)
                      {
                          myAuthor = titleAuthorInfo.Groups["name"].Value.Trim();
                          if (!string.IsNullOrEmpty(myAuthor))
                          {
                              authorFound = true;
                          }

                      }
                  }

                  if (publisherInfo.Success)
                  {
                      if (!publisherFound)
                      {
                          myPublisher = publisherInfo.Groups["publisher"].Value.Trim();
                          if (!string.IsNullOrEmpty(myPublisher))
                          {
                              publisherFound = true;
                          }
                      }
                  }
                  if (titleFound && authorFound && publisherFound)
                  {
                      break;
                  }
              }


              //((TextBox)dvwProduct.FindControl.FindControl("bookPublisher")).Text = myPublisher;
              ((TextBox)dvwProduct.FindControl("txtTitle")).Text = myTitle;
              ((TextBox)dvwProduct.FindControl("txtAuthor")).Text = myAuthor;
              ((Button)dvwProduct.FindControl("fetchBtn")).Enabled = true;
          }
          catch (System.Net.WebException err)
          {
              ((Label)this.errLabel).Text =
                  "There was an error with the fetch service.  Try again or enter data manually.";
              ((Button)dvwProduct.FindControl("fetchBtn")).Enabled = true;
          }

          catch (Exception err)
          {
              ((Label)this.errLabel).Text = err.Message;
          }

      }
}
}